package com.supermarket.service;

import com.supermarket.entity.Favorites;
import com.supermarket.mapper.FavoritesMapper;
import com.supermarket.common.RedisUtil;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Set;

/**
 * 收藏夹服务实现类
 */
@Service
public class FavoritesService {
    
    @Resource
    private FavoritesMapper favoritesMapper;
    
    @Resource
    private RedisUtil redisUtil;
    
    // Redis缓存相关的Key前缀
    private static final String FAVORITES_USER_KEY = "favorites:user:";
    private static final String FAVORITES_STATUS_KEY = "favorites:status:";
    private static final int FAVORITES_CACHE_SECONDS = 3600; // 收藏夹缓存默认1小时

    /**
     * 添加收藏
     * 
     * @param userId 用户ID
     * @param commodityId 商品ID
     * @return 操作结果
     */
    @Transactional
    public int addFavorites(Integer userId, Integer commodityId) {
        // 先检查是否已收藏
        Favorites existFavorites = favoritesMapper.selectByUserIdAndCommodityId(userId, commodityId);
        if (existFavorites != null) {
            // 已收藏，直接返回成功
            return 1;
        }
        
        // 未收藏，创建新收藏
        Favorites favorites = new Favorites();
        favorites.setUserId(userId);
        favorites.setCommodityId(commodityId);
        int result = favoritesMapper.insert(favorites);
        
        // 清除用户收藏缓存
        if (result > 0) {
            clearUserFavoritesCache(userId);
            clearFavoritesStatusCache(userId, commodityId);
        }
        
        return result;
    }
    
    /**
     * 取消收藏
     * 
     * @param userId 用户ID
     * @param commodityId 商品ID
     * @return 操作结果
     */
    @Transactional
    public int removeFavorites(Integer userId, Integer commodityId) {
        int result = favoritesMapper.deleteByUserIdAndCommodityId(userId, commodityId);
        
        // 清除用户收藏缓存
        if (result > 0) {
            clearUserFavoritesCache(userId);
            clearFavoritesStatusCache(userId, commodityId);
        }
        
        return result;
    }
    
    /**
     * 根据ID删除收藏
     * 
     * @param id 收藏ID
     * @return 操作结果
     */
    @Transactional
    public int deleteFavorites(Integer id) {
        // 先获取收藏信息，以便清除缓存
        // 由于FavoritesMapper没有selectById方法，我们先删除再清除所有缓存
        int result = favoritesMapper.deleteById(id);
        
        // 清除所有收藏相关缓存
        if (result > 0) {
            // 清除所有用户收藏缓存
            Set<String> userKeys = redisUtil.keys(FAVORITES_USER_KEY + "*");
            if (userKeys != null && !userKeys.isEmpty()) {
                redisUtil.delete(userKeys);
            }
            
            // 清除所有收藏状态缓存
            Set<String> statusKeys = redisUtil.keys(FAVORITES_STATUS_KEY + "*");
            if (statusKeys != null && !statusKeys.isEmpty()) {
                redisUtil.delete(statusKeys);
            }
        }
        
        return result;
    }
    
    /**
     * 清空用户收藏夹
     * 
     * @param userId 用户ID
     * @return 操作结果
     */
    @Transactional
    public int clearFavorites(Integer userId) {
        int result = favoritesMapper.deleteByUserId(userId);
        
        // 清除用户收藏缓存
        if (result > 0) {
            clearUserFavoritesCache(userId);
            // 清除该用户所有商品的收藏状态缓存
            Set<String> statusKeys = redisUtil.keys(FAVORITES_STATUS_KEY + userId + ":*");
            if (statusKeys != null && !statusKeys.isEmpty()) {
                redisUtil.delete(statusKeys);
            }
        }
        
        return result;
    }
    
    /**
     * 查询用户是否已收藏某商品
     * 
     * @param userId 用户ID
     * @param commodityId 商品ID
     * @return 是否已收藏
     */
    public boolean isFavorite(Integer userId, Integer commodityId) {
        String cacheKey = FAVORITES_STATUS_KEY + userId + ":" + commodityId;
        
        // 尝试从缓存获取
        Object cached = redisUtil.get(cacheKey);
        if (cached != null) {
            return (boolean) cached;
        }
        
        // 缓存未命中，查询数据库
        boolean isFavorite = favoritesMapper.selectByUserIdAndCommodityId(userId, commodityId) != null;
        
        // 将结果存入缓存
        redisUtil.set(cacheKey, isFavorite, FAVORITES_CACHE_SECONDS);
        
        return isFavorite;
    }
    
    /**
     * 获取用户收藏列表
     * 
     * @param userId 用户ID
     * @return 收藏列表
     */
    public List<Favorites> getUserFavorites(Integer userId) {
        String cacheKey = FAVORITES_USER_KEY + userId;
        
        // 尝试从缓存获取
        Object cached = redisUtil.get(cacheKey);
        if (cached != null) {
            return (List<Favorites>) cached;
        }
        
        // 缓存未命中，查询数据库
        List<Favorites> favorites = favoritesMapper.selectByUserId(userId);
        
        // 将结果存入缓存
        if (favorites != null && !favorites.isEmpty()) {
            redisUtil.set(cacheKey, favorites, FAVORITES_CACHE_SECONDS);
        }
        
        return favorites;
    }
    
    /**
     * 清除用户收藏缓存
     */
    private void clearUserFavoritesCache(Integer userId) {
        if (userId != null) {
            redisUtil.delete(FAVORITES_USER_KEY + userId);
        }
    }
    
    /**
     * 清除收藏状态缓存
     */
    private void clearFavoritesStatusCache(Integer userId, Integer commodityId) {
        if (userId != null && commodityId != null) {
            redisUtil.delete(FAVORITES_STATUS_KEY + userId + ":" + commodityId);
        }
    }
}
